#!/usr/bin/env python3
import sys
import os
import io
import runpy
import platform
import warnings

## 忽略 pydub\utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work
warnings.filterwarnings("ignore", category=RuntimeWarning)

# 修复中文控制台输出
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

if platform.system() == "Windows":
    import ctypes
    try:
        ctypes.windll.kernel32.SetConsoleCP(65001)
        ctypes.windll.kernel32.SetConsoleOutputCP(65001)
    except Exception:
        pass

def main():
    if getattr(sys, 'frozen', False):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.dirname(os.path.abspath(__file__))

    markitdown_path = os.path.join(base_path, "markitdown")
    if markitdown_path not in sys.path:
        sys.path.insert(0, markitdown_path)

    # 修正 magika 模型目录
    try:
        import magika
        magika_root = os.path.join(base_path, "magika")
        models_path = os.path.join(magika_root, "models")
        if hasattr(magika.magika, "MAGIKA_MODELS_DIR"):
            magika.magika.MAGIKA_MODELS_DIR = models_path
        else:
            os.environ["MAGIKA_MODELS_DIR"] = models_path
    except Exception:
        pass

    runpy.run_module("markitdown", run_name="__main__")

if __name__ == "__main__":
    main()
